{{define "register"}}
<div class="form-container">
    <h2>用户注册</h2>

    {{if .Error}}
    <div class="alert error">{{.Error}}</div>
    {{end}}
    {{if .Success}}
    <div class="alert success">{{.Success}}</div>
    {{end}}

    <form id="registerForm" class="register-form">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit" class="btn">注册</button>
    </form>
    <p>已有账号？<a href="/auth/loginPage">立即登录</a></p>
</div>

<script>
    // 拦截表单提交，使用AJAX异步请求
    document.getElementById('registerForm').addEventListener('submit', function(e) {
        e.preventDefault(); // 阻止表单默认提交

        // 显示加载状态
        const submitBtn = this.querySelector('button');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="btn-loading">注册中...</span>';

        // 收集表单数据
        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        // 异步调用注册接口
        fetch('/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(result => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = '注册';

                if (result.code === '00000') { // 假设成功状态码为0000
                    // 注册成功，显示提示并跳转登录页
                    const successEl = document.createElement('div');
                    successEl.className = 'alert success';
                    successEl.innerHTML = `${result.message} <a href="/auth/loginPage">立即登录</a>`;
                    this.insertBefore(successEl, this.firstChild);
                } else {
                    // 显示错误信息
                    const errorEl = document.createElement('div');
                    errorEl.className = 'alert error';
                    errorEl.textContent = result.message || '注册失败，请重试';
                    this.insertBefore(errorEl, this.firstChild);
                }
            })
            .catch(error => {
                // 网络错误处理
                submitBtn.disabled = false;
                submitBtn.innerHTML = '注册';
                const errorEl = document.createElement('div');
                errorEl.className = 'alert error';
                errorEl.textContent = '网络错误，请检查连接';
                this.insertBefore(errorEl, this.firstChild);
            });
    });
</script>
{{end}}

{{template "base.html" .}}